/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.controllers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.database.Database;
import org.database.DatabaseEmre;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.property.Estate;
import org.property.House;
import org.users.Agent;
import org.users.Customer;

/**
 *
 * @author Emre
 */
@ManagedBean(name = "agentbean")
@ViewScoped
public class AgentBean {

    private List<Agent> agents;
    private List<House> houses;
    private List<Estate> estates;
    private static House selectedHouse = new House();
    private Database database;
    private DatabaseEmre databaseEmre;
    private List<String> uploadedEstateImages = new LinkedList<String>();
    private static Customer customer = new Customer();
    private List<Customer> customers;
    private String effect = "fade";
    private static Estate selectedEstate = new Estate();
    private Map<String, String> cities = new HashMap<String, String>();
    private Map<String, String> types = new HashMap<String, String>();
    private Map<String, Map<String, String>> suburbsData = new HashMap<String, Map<String, String>>();
    private Map<String, String> suburbs = new HashMap<String, String>();
    private String city = "";
    private String suburb;
    private String type;
    private static Agent agent = new Agent();
    private House house;
    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    
    

    public String getEffect() {
        return effect;
    }

    @PostConstruct
    public void init() {
        images = new ArrayList<String>();
        imagesHouse = new ArrayList<String>();
        if(selectedEstate != null){
        images = selectedEstate.getImageList();
        }
        if(selectedHouse != null){
        imagesHouse = selectedHouse.getImageList();
        }
    }

    public Estate getSelectedEstate() {
        return selectedEstate;
    }

    public void setSelectedEstate(Estate selectedEstate) {
        this.selectedEstate = selectedEstate;
    }

    public Agent getAgent() {
        return agent;
    }

    public void setAgent(Agent agent) {
        this.agent = agent;
    }

    public House getHouse() {
        return house;
    }

    public void setHouse(House house) {
        this.house = house;
    }

    public Map<String, String> getCities() {
        return cities;
    }

    public void setCities(Map<String, String> cities) {
        this.cities = cities;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSuburb() {
        return suburb;
    }

    public void setSuburb(String suburb) {
        this.suburb = suburb;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }

    public Map<String, String> getSuburbs() {
        return suburbs;
    }

    public void setSuburbs(Map<String, String> suburbs) {
        this.suburbs = suburbs;
    }

    public Map<String, Map<String, String>> getSuburbsData() {
        return suburbsData;
    }

    public void setSuburbsData(Map<String, Map<String, String>> suburbsData) {
        this.suburbsData = suburbsData;
    }

    public Map<String, String> getTypes() {
        return types;
    }

    public void setTypes(Map<String, String> types) {
        this.types = types;
    }

    public List<String> getUploadedEstateImages() {
        return uploadedEstateImages;
    }

    public void setEffect(String effect) {
        this.effect = effect;
    }

    public List<String> getImages() {
        return images;
    }

    public void setImages(List<String> images) {
        this.images = images;
    }
    private List<String> images;
    private List<String> imagesHouse;

    public List<String> getImagesHouse() {
        return imagesHouse;
    }

    public void setImagesHouse(List<String> imagesHouse) {
        this.imagesHouse = imagesHouse;
    }
    
    

    public void setUploadedEstateImages(List uploadedEstateImages) {
        this.uploadedEstateImages = uploadedEstateImages;
    }

    public List<Estate> getEstates() {
        return estates;
    }

    public void setEstates(List<Estate> estates) {
        this.estates = estates;
    }

    public void showEstateDetails() throws IOException {
        images = selectedEstate.getImageList();
        if (images.isEmpty()) {
            System.out.print("liste bos");
        } else {
            for (String i : images) {
                System.out.print(i);
            }

        }
        FacesContext.getCurrentInstance().getExternalContext().redirect("AgentEstateDetails.xhtml");
        //   return  "testestatedetails.xhtml";
    }

    /** Creates a new instance of AgentBean */
    public AgentBean() throws SQLException, ClassNotFoundException {
        agents = new ArrayList<Agent>();
        database = new Database();
        databaseEmre = new DatabaseEmre();
        houses = new ArrayList<House>();
        estates = new ArrayList<Estate>();
        house = new House();
        customers = new ArrayList<Customer>();
        types.put("Sale", "1");
        types.put("Rent", "2");
        Database db = new Database();
        db.connect();
        cities = db.getCitiesMap();
        suburbsData = db.getSuburbsMap();
        db.disconnect();
        listCustomers();
        listHouses();
        listEstates();
    }
    
        public void showHouseDetails() throws IOException {
        imagesHouse = selectedHouse.getImageList();

        FacesContext.getCurrentInstance().getExternalContext().redirect("AgentHouseDetails.xhtml");
    }
        


    public void listEstates() throws ClassNotFoundException, SQLException {

        databaseEmre.connect();
        estates = databaseEmre.getEstateList();
        databaseEmre.disconnect();
    }

    public void handleCityChange() {
        if (city != null && !city.equals("")) {
            suburbs = suburbsData.get(city);
        } else {
            suburbs = new HashMap<String, String>();
        }
    }

    public void listHouses() throws SQLException, ClassNotFoundException {
        databaseEmre.connect();
        houses = databaseEmre.getHouseList();
        databaseEmre.disconnect();
    }

    public void deleteHouse() throws ClassNotFoundException, SQLException {
        databaseEmre.connect();
        databaseEmre.deleteHouse(selectedHouse);
        databaseEmre.disconnect();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Record is deleted successfully !"));

    }

    public List<Agent> getAgents() {
        return agents;
    }

    public void setAgents(List<Agent> agents) {
        this.agents = agents;
    }

    public Database getDatabase() {
        return database;
    }

    public void setDatabase(Database database) {
        this.database = database;
    }

    public DatabaseEmre getDatabaseEmre() {
        return databaseEmre;
    }

    public void setDatabaseEmre(DatabaseEmre databaseEmre) {
        this.databaseEmre = databaseEmre;
    }

    public List<House> getHouses() {
        return houses;
    }

    public void setHouses(List<House> houses) {
        this.houses = houses;
    }

    public House getSelectedHouse() {
        return selectedHouse;
    }

    public void setSelectedHouse(House selectedHouse) {
        this.selectedHouse = selectedHouse;
    }
    
        public void login() throws SQLException, ClassNotFoundException, IOException {
        DatabaseEmre db = new DatabaseEmre();
        db.connect();
        agent = db.agentLogin(username, password);
        if(agent != null){
            FacesContext.getCurrentInstance().getExternalContext().redirect("Agent.xhtml");
        }
        else{
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Username and/or password is wrong. Please try again !"));
        }
               
        db.disconnect();
    }
        
      public void logout() throws IOException{
            agent = null;
              FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
      }  

    public void handleFileUpload(FileUploadEvent event) throws IOException {
        UploadedFile file = event.getFile();
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        File newFile = new File(extContext.getRealPath("//Images") + "//" + event.getFile().getFileName());
        System.out.println(System.getProperty("user.home") + File.separator + file.getFileName());
        System.out.println(extContext.getRealPath("//Images") + "//" + event.getFile().getFileName());
        FileOutputStream fileOutputStream = new FileOutputStream(newFile);
        uploadedEstateImages.add(event.getFile().getFileName());
        byte[] buffer = new byte[6124];

        int bulk;
        InputStream inputStream = event.getFile().getInputstream();
        while (true) {
            bulk = inputStream.read(buffer);
            if (bulk < 0) {
                break;
            }
            fileOutputStream.write(buffer, 0, bulk);
            fileOutputStream.flush();
        }

        fileOutputStream.close();
        inputStream.close();

        FacesMessage msg = new FacesMessage("Succesful",
                event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);


    }

    public void addCustomer() throws ClassNotFoundException, SQLException {
        customer.setAddressDistrict(suburb);
        customer.setAddressProvince(city);

        databaseEmre.connect();
        databaseEmre.addCustomer(customer);
        databaseEmre.disconnect();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Record is saved successfully !"));
    }

    public void deleteCustomer() throws ClassNotFoundException, SQLException {
        databaseEmre.connect();
        databaseEmre.deleteCustomer(customer);
        customers = databaseEmre.getCustomerList();
        databaseEmre.disconnect();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Record is deleted successfully !"));
    }

    public void listCustomers() throws ClassNotFoundException, SQLException {
        databaseEmre.connect();
        customers = databaseEmre.getCustomerList();
        databaseEmre.disconnect();
    }

    public void updateCustomer() throws ClassNotFoundException, SQLException {
        customer.setAddressDistrict(suburb);
        customer.setAddressProvince(city);

        databaseEmre.connect();
        databaseEmre.updateCustomer(customer);
        databaseEmre.disconnect();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Record is updated successfully !"));
    }

    public void deleteEstate() throws ClassNotFoundException, SQLException {


        DatabaseEmre db = new DatabaseEmre();
        db.connect();
        db.deleteEstate(selectedEstate);
        estates = db.getEstateList();
        db.disconnect();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Record is deleted successfully !"));


    }

    public void sellOrRentHouse() throws ClassNotFoundException, SQLException {
        databaseEmre.connect();
        databaseEmre.agentSellHouse(agent.getTC_ID(), selectedHouse.getCustomerId(), selectedHouse.getId());
        databaseEmre.disconnect();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Operation was performed successfully !"));
    }

    public void sellOrRentEstate() throws ClassNotFoundException, SQLException {
        databaseEmre.connect();
        databaseEmre.agentSellEstate(agent.getTC_ID(), selectedEstate.getCustomerId(), selectedEstate.getId());
        databaseEmre.disconnect();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Operation was performed successfully !"));
    }
}
